/*
 * @Author: xuhua
 * @Date: 2023-09-13 16:34:11
 * @LastEditors: xuhua
 * @LastEditTime: 2023-09-19 13:52:14
 * @FilePath: /v3-element-admin/src/permission.ts
 * @Description:
 */
import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStore } from "@/store/modules/permission";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // 进度条

// 白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
	NProgress.start();
	const hasToken = localStorage.getItem("accessToken");

	if (hasToken) {
		if (to.path === "/login") {
			next({ path: `/` });
			NProgress.done();
		} else {
			const userStore = useUserStoreHook();
			const hasRoles = userStore.user.roles && userStore.user.roles.length > 0;

			if (hasRoles) {
				// 未匹配到路由,去404
				if (to.matched.length === 0) {
					from.name ? next({ name: from.name }) : next("/404");
				} else {
					next();
				}
			} else {
				try {
					const permissionStore = usePermissionStore();
					// 获取角色,根据角色获取处理异步路由
					const { roles } = await userStore.getInfo();

					// TODO 获取异步路由,
					const accessRoutes = await permissionStore.generateRoutes(roles);
					accessRoutes.forEach((route) => {
						router.addRoute(route);
					});
					next({ ...to, replace: true });
				} catch (error) {
					// 移出token,跳到login
					await userStore.resetStore();
					next(`/login?redirect=${to.path}`);
					NProgress.done();
				}
			}
		}
	} else {
		// 未登录可以访问白名单,判断是否在白名单
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next(`/login?redirect=${to.path}`);
			NProgress.done();
		}
	}
});
